<template lang="pug">
  .gather
    Card.gather-header
      span 任务名称：
      Input(v-model='taskName',search,enter-button="查询",placeholder='任务名称',:maxlength="50",@on-search='handleUpdateTableData()')
      Button(v-if="$route.meta['/task/add']",@click="$router.push({name:'task_index',query:{status:'add'}})") 新增
    Card.gather-body
      Tabs(v-model='tabPaneActive')
        TabPane(v-for="(item, index) in tabData",:label='item.label',:name='item.name',:key="index")
      site-list(ref='taskSite',:siteLists="taskList.siteLists",@changeSite='handleChangeSite')
      show-table(ref='taskList',:total='taskList.total',:current='taskList.current',:columns="taskList.columns",:data='taskList.tabData',@handleChangePage='handleChangePage')
</template>

<script>
import asyncGather from './api'
import siteList from '@/components/site-list/site-list'
import showTable from '@/components/show-table/show-table'

export default {
  name: 'Gather',
  components: { siteList, showTable },
  data() {
    return {
      tabData: [{ label: '任务列表', name: '0' }, { label: '回收站', name: '1' }],
      siteId: '',
      siteIndex: '',
      taskName: '',
      tabPaneActive: '0',
      taskList: {
        total: 0,
        current: 1,
        columns: [],
        tabData: [],
        siteLists: [{ siteName: '全部', siteId: '' }]
      },
      columnCommon: [
        { title: 'ID', width: 50, align: 'center', key: 'taskId' },
        {
          title: '任务名称',
          render: (h, params) => {
            if (this.tabPaneActive === '0' && this.$route.meta['/task/query']) {
              const taskqueryData = {
                status: 'modify',
                taskId: params.row.taskId,
                taskStatus: params.row.status,
                checkType: params.row.checkType.toString(),
                updatePersonId: params.row.updatePersonId.toString()
              }
              return h('Tooltip', { attrs: { placement: 'top-start', content: `${params.row.taskName}` } }, [
                h('router-link', { attrs: { to: { name: 'task_index', query: taskqueryData } } }, params.row.taskName)
              ])
            } else {
              return h('Tooltip', { attrs: { placement: 'top-start', content: `${params.row.taskName}` } }, params.row.taskName)
            }
          }
        },
        {
          title: '有效时间',
          width: 90,
          align: 'center',
          render: (h, params) => {
            if (params.row.startTime !== undefined) return h('span', `${params.row.startTimes.split(' ')[0]} ~ ${params.row.endTimes.split(' ')[0]}`)
          }
        },
        { title: '创建时间', width: 80, align: 'center', key: 'createTimes' },
        {
          title: '上次运行时间',
          width: 90,
          align: 'center',
          render: (h, params) => {
            if (params.row.lastCrawlTimes !== null && params.row.lastCrawlTimes === '0') {
              return h('div', '0')
            } else if (params.row.lastCrawlTimes === '-') {
              return h('span', '-')
            } else {
              return h('div', [h('p', `${params.row.lastCrawlTimes.split(' ')[0]}`), h('p', `${params.row.lastCrawlTimes.split(' ')[1]}`)])
            }
          }
        },
        { title: '创建人', width: 80, align: 'center', key: 'createName' },
        {
          title: '优先级',
          width: 60,
          align: 'center',
          render: (h, params) => {
            switch (params.row.priority) {
              case 1:
                return h('span', '高')
              case 2:
                return h('span', '中')
              case 3:
                return h('span', '低')
            }
          }
        },
        {
          title: '签出状态',
          width: 110,
          align: 'center',
          render: (h, params) => {
            switch (params.row.checkType) {
              case 0:
                return h('Tooltip', { attrs: { placement: 'top-start', content: `已签出${params.row.updatePersonName}` } }, [
                  h('span', { class: { checkout: true } }, `已签出${params.row.updatePersonName}`)
                ])
              case 1:
                return h('span', { class: { checkin: true } }, '已签入')
            }
          }
        },
        { title: '签出时间', width: 80, align: 'center', key: 'updateTimes' },
        {
          title: '当前状态',
          width: 80,
          align: 'center',
          render: (h, params) => {
            const createElement = (color, text, leftPd) => {
              return h('p', [h('Icon', { style: { color, marginLeft: leftPd, marginRight: '5px' }, attrs: { type: 'md-radio-button-on' } }), h('span', text)])
            }
            switch (params.row.status) {
              case 0:
                return createElement('#9b9b9b', '停止', '-10px')
              case 1:
                return createElement('#3dbd7d', '运行中')
              case 2:
                return createElement('#ffbf00', '暂停', '-10px')
              case 3:
                return createElement('#ffbf00', '删除', '-10px')
              case 4:
                return createElement('#108ee9', '已完成')
              default:
                return createElement('#f04134', '异常', '-10px')
            }
          }
        },
        {
          title: '进度',
          width: 60,
          align: 'center',
          render: (h, params) => {
            const pro = params.row.speedOfProgress
            if (pro > 100) pro = 100
            return h('span', `${pro}%`)
          }
        },
        {
          title: '抽取率',
          width: 55,
          align: 'center',
          render: (h, params) => {
            const rate = params.row.extractionRate
            if (rate > 100) rate = 100
            return rate > 0 ? h('span', `${rate}%`) : h('span', rate)
          }
        }
      ],
      listLastColumn: [
        {
          title: '操作',
          width: 170,
          render: (h, params) => {
            const ceaseFunc = h('Button', {
              attrs: { title: '停止', icon: 'ios-skip-forward' },
              style: { color: '#ffbf00', background: '#f7f7f7' },
              class: { 'operate-btn': true },
              on: { click: () => this.handleTaskStatus(params.row.taskId, 0, params.index) }
            })
            const startFunc = h('Button', {
              attrs: { title: '启动', icon: 'ios-play' },
              style: { color: '#329a23', padding: '3px 12px', background: '#f7f7f7' },
              class: { 'operate-btn': true },
              on: { click: () => this.handleTaskStatus(params.row.taskId, 1, params.index) }
            })
            const pauseFunc = h('Button', {
              attrs: { title: '暂停', icon: 'ios-pause' },
              style: { color: '#108ee9', background: '#f7f7f7' },
              class: { 'operate-btn': true },
              on: { click: () => this.handleTaskStatus(params.row.taskId, 2, params.index) }
            })
            const updateFunc = h('Button', {
              attrs: { title: '重新启动', icon: 'md-refresh' },
              style: { color: '#329a23', background: '#f7f7f7' },
              class: { 'operate-btn': true },
              on: { click: () => this.handleTaskStatus(params.row.taskId, 4, params.index) }
            })
            const deleteFunc = h(
              'Poptip',
              {
                attrs: { confirm: true, title: '确定要删除这条任务吗?', placement: 'top-end', width: 200 },
                on: { 'on-ok': () => this.handleTaskDelete(params.row.taskId, params.index) }
              },
              [h('Button', { attrs: { icon: 'md-trash', title: '删除' }, style: { color: '#f04134', background: '#f7f7f7' }, class: { 'operate-btn': true } })]
            )
            let [taskStatus, deleteStatus] = [[], []]
            if (this.$route.meta['/task/updateTaskStatus']) {
              switch (params.row.status) {
                case 0:
                  taskStatus = [updateFunc]
                  break
                case 1:
                  taskStatus = [pauseFunc, ceaseFunc]
                  break
                case 2:
                  taskStatus = [startFunc, ceaseFunc]
                  break
                case 4:
                  taskStatus = [updateFunc]
                  break
                default:
                  taskStatus = [startFunc]
                  break
              }
            }
            if (this.$route.meta['/task/delete']) deleteStatus = [deleteFunc]
            return h('div', [...taskStatus, ...deleteStatus])
          }
        }
      ],
      recycleLastColumn: [
        {
          title: '操作',
          width: 75,
          align: 'center',
          render: (h, params) => {
            return h(
              'Poptip',
              {
                attrs: { confirm: true, title: '确定要恢复这条任务吗?', placement: 'top-end', width: 200 },
                on: { 'on-ok': () => this.handleTaskRecover(params.row.taskId, 0, params.index) }
              },
              [h('Button', { attrs: { icon: 'md-refresh', title: '恢复' }, style: { color: '#329a23' }, class: { 'operate-btn': true } })]
            )
          }
        }
      ]
    }
  },
  watch: {
    tabPaneActive(name) {
      this.tabPaneActive = name
      this.$refs['taskSite'].showSiteId = this.siteId = ''
      this.handleUpdateTableData()
      this.handleSiteList('taskList', 'taskSite', this.tabPaneActive === '0' ? { typeId: 0 } : { typeId: 0, isDelete: 1 })
      name === '0' ? (this.taskList.columns = [...this.columnCommon, ...this.listLastColumn]) : (this.taskList.columns = [...this.columnCommon, ...this.recycleLastColumn])
    }
  },
  mounted() {
    this.taskList.columns = [...this.columnCommon, ...this.listLastColumn]
    this.handleSiteList('taskList', 'taskSite', { typeId: 0 })
    this.handleTableData('taskList', 'taskList')
  },
  methods: {
    handleSiteList: async function(obj, identity, config) {
      /**
       * @param {String} obj 站点组件对象
       * @param {String} lists 站点组件属性
       * @param {String} identity 站点组件ref
       */
      const self = this
      try {
        self[obj].siteLists = [{ siteName: '全部', siteId: '' }]
        self[obj].siteLists = [...self[obj].siteLists, ...(await asyncGather.sitenum({ data: config })).data.data]
        self.$refs[identity].showSitePanel = false
        if (self[obj].siteLists.length - 1 > self.$refs[identity].showSiteMax) {
          self.$refs[identity].showSitePanel = true
        }
      } catch (error) {}
    },
    handleTableData: async function(obj, identity, taskStatus = 1) {
      /**
       * @param {String} obj table 数据对象
       * @param {String} identity table ref
       */
      const self = this
      try {
        self[obj].total = 0
        self[obj].tabData = []
        self.$refs[identity].loading = true
        const res = await asyncGather.list({
          params: { pageIndex: self[obj].current, pageSize: self.$refs[identity].pageSize, siteId: this.siteId, taskName: this.taskName, taskStatus }
        })
        self[obj].total = res.data.data.recordCount
        self[obj].tabData = res.data.data.result
        self.$refs[identity].loading = false
      } catch (error) {
        self.$refs[identity].loading = false
      }
    },
    handleUpdateTableData(current = 1) {
      this.taskList.current = current
      this.handleTableData('taskList', 'taskList', this.tabPaneActive === '0' ? 1 : 0)
    },
    handleChangeSite(siteId, index) {
      this.siteIndex = index
      this.siteId = siteId
      this.handleUpdateTableData()
    },
    handleChangePage(pageSub) {
      this.handleUpdateTableData(pageSub)
    },
    handleTaskStatus: async function(taskId, status, index) {
      try {
        await asyncGather.updateTaskStatus({ data: { taskId, status } })
        if (status === 4) this.taskList.tabData[index].status = 1
        else this.taskList.tabData[index].status = status
      } catch (error) {}
    },
    handleTaskDelete: async function(taskId, index) {
      try {
        await asyncGather.delete({ data: { taskId } })
        this.handleTaskCommonAction(index)
      } catch (error) {}
    },
    handleTaskRecover: async function(taskId, status, index) {
      try {
        await this.handleTaskStatus(taskId, status, index)
        this.handleTaskCommonAction(index)
      } catch (error) {}
    },
    handleTaskCommonAction(index) {
      this.taskList.tabData.splice(index, 1)
      this.handleUpdateTableData(this.taskList.tabData.length !== 0 ? this.taskList.current : --this.taskList.current !== 0 ? this.taskList.current : (this.taskList.current = 1))
      --this.$refs['taskSite'].siteLists[this.siteIndex].number
      if (this.$refs['taskSite'].siteLists[this.siteIndex].number === 0) {
        this.$refs['taskSite'].showSiteId = this.siteId = ''
        this.handleSiteList('taskList', 'taskSite', this.tabPaneActive === '0' ? { typeId: 0 } : { typeId: 0, isDelete: 1 })
        this.handleUpdateTableData()
      }
    }
  }
}
</script>

<style lang="scss">
@import './index.scss';
</style>
